package com.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringWriter;
import java.io.UnsupportedEncodingException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.jdom.Document;
import org.jdom.Element;
import org.jdom.input.SAXBuilder;
import org.jdom.output.Format;
import org.jdom.output.XMLOutputter;

import com.entity.Function;
import com.entity.UserCookieInfo;
import com.google.gson.Gson;


public class AppUtil {
	private static final Log log = LogFactory.getLog(AppUtil.class);
	
	private AppUtil() {
		
	}
	 /*****
	  *字符串转换为整形
	  * @param value
	  * @return
	  */
	 public static int ObjectToInt(Object value){
		 int va=0;
		 try{
			 if(value!=null)
				 va=Integer.parseInt(String.valueOf(value));
		 }catch(Exception ex){
			 log.error(ex.getMessage());
			 ex.printStackTrace();
		 }
		 return va;
	 }
	 
	 /*****
	  *字符串转换为long
	  * @param value
	  * @return
	  */
	 public static long ObjectToLong(Object value){
		 long va=0;
		 try{
			 if(value!=null)
				 va=Long.valueOf(String.valueOf(value));
		 }catch(Exception ex){
			 log.error(ex.getMessage());
			 ex.printStackTrace();
		 }
		 return va;
	 }
	 public static String ObjectToString(Object value){
		 String va="";
		 try{
			 if(value!=null)
				 va=String.valueOf(value).equals("null")?"":String.valueOf(value);
		 }catch(Exception ex){
			 log.error(ex.getMessage());
			 ex.printStackTrace();
		 }
		 return va;
	 }
	 /*****
	  * 日期转换为字符串
	  * @param value
	  * @param type
	  * @return
	  */
	 public static String DateToString(Date value,String type){
		    SimpleDateFormat df = new SimpleDateFormat(type);
		    String str=null;
		    try{
		    	str=df.format(value);
		    }catch(Exception ex){
		    	ex.printStackTrace();
		    	log.error("DateToString is error !!");
		    }
		 return str;
	 }
	 /*****
	  * 日期转换为字符串
	  * @param value
	  * @param type
	  * @return
	  */
	 public static String DateToString(Date value){
		    SimpleDateFormat df = new SimpleDateFormat();
		    String str=null;
		    try{
		    	str=df.format(value);
		    }catch(Exception ex){
		    	ex.printStackTrace();
		    	log.error("DateToString is error !!");
		    }
		 return str;
	 }
	 /*****
	  * 字符串转换为日期
	  * @param value
	  * @param type
	  * @return
	  */
	 public static Date StringToDate(String value,String type){
		    SimpleDateFormat df = new SimpleDateFormat(type);
		    Date str=null;
		    try{
		    	str=df.parse(value);
		    }catch(Exception ex){
		    	ex.printStackTrace();
		    	log.error("StringToDate is error !!");
		    }
		 return str;
	 }
	 
	 /*****
	  * 字符串转换为日期
	  * @param value
	  * @param type
	  * @return
	  */
	 public static Date StringToDateYYYYMMDD(String value){
		    SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		    Date str=null;
		    try{
		    	str=df.parse(value);
		    }catch(Exception ex){
		    	ex.printStackTrace();
		    	log.error("StringToDate is error !!");
		    }
		 return str;
	 }
	 /******
	  * Object 转换 float 
	  * @param key
	  * @return
	  */
	 public static float ObjectToFloat(Object key){
		 float value=0;
		 try{
			 if(null!=key&&!String.valueOf(key).equalsIgnoreCase("null"))
				 value=Float.valueOf(String.valueOf(key));
			 
		 }catch(Exception ex){
			 ex.printStackTrace();
			 log.error("ObjectToFloat is error !!! ");
		 }
		 
		 return value;
	 }
	 
	 /*******
	  * 订单类型转换
	  * @param type
	  * @return
	  */
	 public static String getOrderState(int type){
		 String value=null;
		 switch(type){
				 case 1: value="等待确认";break;
				 case 2: value="订单作废";break;
				 case 3: value="客人确认订单";break;
				 case 4: value="订单作废";break;
				 case 5: value="饭店取消";break;
				 case 6: value="客人未去用餐";break;
				 case 7: value="餐厅无法就餐";break;
				 case 8: value="成功用餐";break;
				 case 9: value="餐厅确认";break;
				 case 10: value="客人准备去用餐";break;
				 case 11: value="客人已回访";break;
				 case 12: value="餐厅确认取消订单";break;
				 case 13: value="客人修改订单";break;
				 case 14: value="客人取消订单";break;
				 case 15: value="餐厅不接受预定";break;
				 
		 }
		 return value;
	 }
	 
	 /******
		 * 计算日期相差几天
		 * @param startDate
		 * @param endDate
		 * @return
		 */
		public static int SubtractForDate(String startDate,String endDate){
			long DAY = 24L * 60L * 60L * 1000L;    
			SimpleDateFormat df = new SimpleDateFormat( "yyyy-MM-dd" );    
			Date d1=null;Date d2=null;int num=0;
			try {
				d1 = df.parse(startDate);
				d2 = df.parse(endDate);    
				num=(int) (( d2.getTime() - d1.getTime() ) / DAY) ;
			} catch (ParseException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}    
			return num;
		}
		/******
		 * 计算日期相差几天
		 * @param startDate
		 * @param endDate
		 * @return
		 */
		public static int SubtractForDate(Date startDate,Date endDate){
			long DAY = 24L * 60L * 60L * 1000L;    
			int num=0;
			try {
				num=(int) (( startDate.getTime() - endDate.getTime() ) / DAY) ;
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}    
			return num;
		}
		
		/******
		 * MD5加密
		 * @param data
		 * @return
		 */
		public static String hash(String data) {
			MessageDigest digest=null;
			try {
				digest = MessageDigest.getInstance("MD5");
				digest.update(data.getBytes());
			} catch (NoSuchAlgorithmException e) {
				e.printStackTrace();
			}
			
			return encodeHex(digest.digest());
		}
		/*****
		 * 返回固定长度
		 * @param bytes
		 * @return
		 */
		private static String encodeHex(byte[] bytes) {
			StringBuffer buf = new StringBuffer(bytes.length * 2);
			int i;
			for (i = 0; i < bytes.length; i++) {
				if ((bytes[i] & 0xff) < 0x10) {
					buf.append("0");
				}
				buf.append(Long.toString(bytes[i] & 0xff, 16));
			}
			return buf.toString().toUpperCase();
		}
		/**
		 * sha-1二次散列加密
		 * @author hanwei (hanwei.1980@hotmail.com)
		 * Create on Mar 26, 2009 2:34:01 PM
		 * @param data
		 * @return
		 */
		public static String SHA1(String data){
			return DigestUtils.shaHex(DigestUtils.sha(data.getBytes()));
		}
		/**
		 * md5二次散列加密
		 * @author hanwei (hanwei.1980@hotmail.com)
		 * Create on Mar 26, 2009 2:34:28 PM
		 * @param data
		 * @return
		 */
		public static String MD5(String data){
			return DigestUtils.md5Hex(DigestUtils.md5(data.getBytes()));
		}

		public static Gson gson(){
			return new Gson();
		}
		
		public static 	String getIP(HttpServletRequest request){

				String ip = request.getHeader("x-forwarded-for");
		        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		            ip = request.getHeader("Proxy-Client-IP");
		       }
		       if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		            ip = request.getHeader("WL-Proxy-Client-IP");
		        }
		        if(ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip)) {
		           ip = request.getRemoteAddr();
		       }
		        return ip;
			}
		/**过滤script,style,html标签
		 * @param inputString
		 * @return
		 */
		public static  String html2Text(String inputString) {    
		      String htmlStr = inputString; //含html标签的字符串    
		      String textStr ="";    
		      java.util.regex.Pattern p_script;    
		      java.util.regex.Matcher m_script;    
		      java.util.regex.Pattern p_style;    
		      java.util.regex.Matcher m_style;    
		      java.util.regex.Pattern p_html;    
		      java.util.regex.Matcher m_html;    
		          
		      try {    
		       String regEx_script = "<[\\s]*?script[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?script[\\s]*?>"; //定义script的正则表达式{或<script>]*?>[\s\S]*?<\/script> }    
		       String regEx_style = "<[\\s]*?style[^>]*?>[\\s\\S]*?<[\\s]*?\\/[\\s]*?style[\\s]*?>"; //定义style的正则表达式{或<style>]*?>[\s\S]*?<\/style> }    
		       String regEx_html = "<[^>]+>"; //定义HTML标签的正则表达式    
		           
		          p_script = Pattern.compile(regEx_script,Pattern.CASE_INSENSITIVE);    
		          m_script = p_script.matcher(htmlStr);    
		          htmlStr = m_script.replaceAll(""); //过滤script标签    
		   
		          p_style = Pattern.compile(regEx_style,Pattern.CASE_INSENSITIVE);    
		          m_style = p_style.matcher(htmlStr);    
		          htmlStr = m_style.replaceAll(""); //过滤style标签    
		           
		          p_html = Pattern.compile(regEx_html,Pattern.CASE_INSENSITIVE);    
		          m_html = p_html.matcher(htmlStr);    
		          htmlStr = m_html.replaceAll(""); //过滤html标签    
		           
		       textStr = htmlStr;    
		           
		      }catch(Exception e) {    
		                  System.err.println("Html2Text: " + e.getMessage());    
		      }    
		          
		      return textStr;//返回文本字符串    
		    }
		/****
		 * 添加用户信息到cookie中
		 * @param response
		 * @param userinfo
		 */
		public static void addUserCookie(HttpServletResponse response, UserCookieInfo userCookieInfo) {
			/**
			 * @link Constant.USERINFO
			 */
			String value = "llt_uci=" + userCookieInfo.getId() + ";" + userCookieInfo.getUsername()  + ";" + userCookieInfo.getPassword()+ ";" + userCookieInfo.getClientid();
			
			Cookie cookies = new Cookie(Constants.LLT_COOKIE_KEY, urlEncoder(value));
			cookies.setPath("/");
			cookies.setSecure(false);
			cookies.setMaxAge(2592000);
			//cookies.setDomain(".fantong.com");
			response.addCookie(cookies);
		}
		/**用户退出以及清除cookie
		 * 
		 * @param request
		 * @param response
		 */
		public static void removeUserCookie(HttpServletResponse response) {
			
			Cookie cookies = new Cookie(Constants.LLT_COOKIE_KEY, "");
			cookies.setPath("/");
			cookies.setSecure(false);
			cookies.setMaxAge(0);
			//cookies.setDomain(".fantong.com");
			response.addCookie(cookies);
		}
		/******
		 * 从cookie中获取用户信息
		 * @param request
		 * @return
		 */
		public static UserCookieInfo getCookieUserInfo(HttpServletRequest request) {
			Cookie[] cs = request.getCookies();
			UserCookieInfo user = null;
			if (cs != null) {
				String str = null;
				for (int i = 0; i < cs.length; i++) {
					if (cs[i].getName().equals(Constants.LLT_COOKIE_KEY)) {
						str = cs[i].getValue();
						break;
					}
				}
				if (str != null && !str.equals("")) {
					str =urlDecoder(str);
					System.out.println("cookies::: "+str);
					String[] tmp = str.split("=");
					if (!tmp[0].equals("llt_uci")) {
						return null;
					}else{
						String[] tpv=tmp[1].split(";");
						user = new UserCookieInfo();
						user.setId(Integer.parseInt(tpv[0]));
						user.setUsername(tpv[1]);
						user.setPassword(tpv[2]);
						user.setClientid(AppUtil.ObjectToInt(tpv[3]));
					}
				}
			}
			return user;
		}
		public static String urlEncoder(String url) {
			if (url != null) {
				try {
					return URLEncoder.encode(url, "UTF-8");
				}
				catch (UnsupportedEncodingException e) {
					log.error(e.getMessage(), e);
				}
			}
			return "";
		}
		public static String urlEncoder(String url, String charset) {
			if (url != null) {
				try {
					return URLEncoder.encode(url, charset);
				}
				catch (UnsupportedEncodingException e) {
					log.error(e.getMessage(), e);
				}
			}
			return "";
		}
		public static String urlDecoder(String url) {
			if (url != null) {
				try {
					return URLDecoder.decode(url, "UTF-8");
				}
				catch (UnsupportedEncodingException e) {
					log.error(e.getMessage(), e);
				}
			}
			return "";
		}
		public static String urlDecoder(String url, String charset) {
			if (url != null) {
				try {
					return URLDecoder.decode(url, charset);
				}
				catch (UnsupportedEncodingException e) {
					log.error(e.getMessage(), e);
				}
			}
			return "";
		}
		/*****
		 * HTTP 请求
		 * @param urlString
		 * @return
		 * @throws IOException
		 */
		public static String sendHttp(String urlString) throws IOException{
			StringBuffer document=new StringBuffer();
			BufferedReader reader =null;
			try {
				URL url = new URL(urlString);
				URLConnection conn = url.openConnection();
				conn.setConnectTimeout(5000);
				conn.setReadTimeout(5000);
				 reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line = null;
				while ( (line = reader.readLine()) != null) {
					document.append(line);
				}
				
			}catch (IOException ex) {
				System.out.println(ex.getMessage());
				return null;
			}finally{
				if(reader!=null) reader.close();
			}
			return 	document.toString();
		}
		
		/*****
		 * HTTP 请求
		 * @param urlString
		 * @return
		 * @throws IOException
		 */
		public static String openURLConnection(String urlString){
			log.info("httpUrl== "+urlString);
			StringBuffer document = new StringBuffer();
			BufferedReader reader =null;
			try {
				URL url = new URL(urlString);
				URLConnection conn = url.openConnection();
				conn.setConnectTimeout(5000);
				conn.setReadTimeout(5000);
				 reader = new BufferedReader(new InputStreamReader(conn.getInputStream()));
				String line = null;
				while ( (line = reader.readLine()) != null) {
					document.append(line);
				}
				
			}catch (IOException ex) {
				System.out.println(ex.getMessage());
				return null;
			}finally{
				if(reader!=null)
					try {
						reader.close();
					} catch (IOException e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
					}
			}
			System.out.println("to======= "+document.toString());
			return 	document.toString();
		}
		
		
		/****
		 * 发送HTTP请求，返回XML
		 * @param xmlPath
		 * @return
		 */
		@SuppressWarnings("unchecked")
		public static  HashMap  sendHTTPBackXML(String httpUrl) throws Exception{
			 HashMap<String, String> hm=null;
//			 log.info("url:"+httpUrl);
				   SAXBuilder bSAX = new SAXBuilder(false);
				   Document doc = bSAX.build(new URL(httpUrl));
				   //Document doc=bSAX.build(new File(xmlPath));   
				   Element  root = doc.getRootElement();
				   List listmsg = root.getChildren();
				   if(listmsg.size()>0) hm=new HashMap<String, String>();
				   for(int i=0;i<listmsg.size();i++){
					   Element catalog = (Element) listmsg.get(i);
					   //是否有子节点 
					   if(catalog.getChildren().size()==0){
						   hm.put(catalog.getName(), catalog.getText());
					   }else{
						   //遍历子节点
						   List<Element> li = catalog.getChildren();
						   for(Element el:li){
							   hm.put(el.getName(), el.getText());
						   }
					   }
				   }
				return hm;
		}
		
		/**
		 * 以流的方式读取Dom对象
		 * @param in
		 * @return
		 */
		public static Document loadDocument(String httpUrl) {
			try {
				URL url = new URL(httpUrl);
				URLConnection conn = url.openConnection();
				conn.setConnectTimeout(5000);
				conn.setReadTimeout(5000);
				org.jdom.input.SAXBuilder builder = new org.jdom.input.SAXBuilder();
				Document doc = builder.build(conn.getInputStream());
				StringWriter strw = new StringWriter();
				XMLOutputter outp = new XMLOutputter(Format.getPrettyFormat());
				outp.output(doc, strw);
//				System.out.println(strw.toString());
				return doc;
			} catch (Exception ex) {
				ex.printStackTrace();
			}
			return null;
		}
		
		
		public static void main(String[] args){
//			String s = "123";
//			System.out.println(hash(s));
//			System.out.println(SHA1(s));
//			System.out.println(MD5(s));
//			ActionInfo info = new ActionInfo();
//			info.setActionid(111);
//			info.setStarttime(new Date());
//			info.setEndtime(new Date());
//			info.setOperatortime(new Date());
//			info.setPublishtime(new Date());
//			info.setRunendtime(new Date());
////			info.setRunstarttime(new Date());
//
//			
//			String json = gson().toJson(info);
//			System.out.println(json);
//			ActionInfo fromjson = gson().fromJson(json, ActionInfo.class);
//			System.out.println(fromjson.getEndtime());
			//System.out.println(StringToDate("2009-04-30 23:12:11", "yyyy-MM-dd HH:mm:ss"));
			//System.out.println(MD5("123456"));
			
			try {
				//sendHttp("http://192.168.1.9:9020/mq/refreshCache/refreshActionInfo4Type.do?clientid=700040278&type=1");
//				openURLConnection("http://192.168.1.10/rs/review_llt_interfaces/cate_review.xml?cate_id=80000123&source_id=3");
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}

		/**
		 * 得到手机号码展示为136****1212形式
		 * @return
		 */
		public static String getMobile4Web(String mobile){
			if(StringUtils.isNotBlank(mobile)){
				 Pattern p = Pattern.compile("0?1[3|5|8]\\d{9}");
				 Matcher m=p.matcher(mobile);
				 if(m.matches()){
					 mobile=mobile.substring(0, 3)+"****"+mobile.substring(mobile.length()-4);
				 }
			}
			return mobile;
		}
		
		/******
		 * 对象转换为json ，使用GSON处理
		 * @param obj 对象
		 */
		public static String Object2Json(Object obj){
			String str = "";
			try{
				Gson gson = new Gson();
				str = gson.toJson(obj);
			}catch(Exception ex){
				ex.printStackTrace();
				log.error("BaseAction 中 gson2String 方法转换出错："+ex.getMessage());
			}
			return str;
		}
		
		
		/**
		 * 
		 * 得到与当天相差几天的字符串
		 */
		public static String getToNowDays(String day_str){
			String s = "";
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			String now_str = sdf.format(new Date());
			day_str = day_str.substring(0,day_str.indexOf(" ")+1);
			int num = AppUtil.SubtractForDate(day_str,now_str);
			switch(num){
				case 0: s= "今天";break;
				case 1: s= "昨天";break;
				case 2: s= "前天";break;
				default : s="前"+num+"天";
			}
			return s;
		}
		
		/**
		 * 以父子关系将功能分类
		 * @param list
		 * @return
		 */
		public String listToMap2(List<Function> list) {
			String jsonFunction = "";
			int parentid = 0,id = 0;
			String functionname = "";
			for (Function function : list) {
				parentid = function.getParentid();
				id = function.getId();
				functionname = function.getFunctionname();
				if(parentid != 0)
				jsonFunction +="{'When':'"+parentid+"','Value':'"+id+"','Text':'"+functionname+"'},";
			}
			if(jsonFunction.lastIndexOf(",")!= -1){
				jsonFunction = jsonFunction.substring(0,jsonFunction.length()-1);
			}
			return jsonFunction;
		}
		
		
}
